package com.sx.pipeline.ui.map

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import androidx.appcompat.widget.SearchView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdate
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.services.core.AMapException
import com.amap.api.services.district.DistrictItem
import com.amap.api.services.district.DistrictSearch
import com.amap.api.services.district.DistrictSearchQuery
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.hjq.bar.TitleBar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.sx.mvvmlibs.binding.edittext.viewAdapter
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.app.base.CYBaseAppBarActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.MyCityPickerListener
import com.sx.pipeline.custom.dialog.MyCityPickerPopup
import com.sx.pipeline.databinding.ActDistrictBorderBinding
import com.sx.pipeline.repos.http.res.ProvincesVO


/**
 * @Author: YY
 * @Date: 2022/8/29
 * @Desc: 行政区边界划分
 */
@Route(path = RoutePath.Main.DISTRICT_BORDER)
class DistrictBorderActivity: CYBaseAppBarActivity<ActDistrictBorderBinding, DistrictBorderVM>
    (com.sx.pipeline.R.layout.act_district_border), View.OnClickListener, SearchView.OnQueryTextListener {

    @Autowired(name = IntentKey.DATA)
    @JvmField
    var name : String? = ""

    // 地图
    private lateinit var aMap: AMap
    // 搜索地址
    private var searchStr: String? = null
    // 行政区域
    private var districtPoints: ArrayList<LatLng> = ArrayList()

    override fun initAppBar() {
        getTitleBar().title = "行政区域查询"
        getTitleBar().setRightTitleColor(Color.parseColor("#333333"))
        getTitleBar().rightTitle = "保存"
    }

    override fun onRightClick(titleBar: TitleBar?) {
        if (TextUtils.isEmpty(name)) {
            if (districtPoints.isNotEmpty()) {
                if (!TextUtils.isEmpty(searchStr)) {
                    mViewModel.addDistrictBorder()
                } else {
                    ToastUtils.showShort("行政区域关键字不能为空")
                }
            } else {
                ToastUtils.showShort("请搜索相关行政区域")
            }
        }
    }

    override fun initData(bundle: Bundle?) {
        super.initData(bundle)
        mBinding.setVariable(BR.onClick, this)
        mBinding.svSearch.setIconifiedByDefault(false)
        mBinding.svSearch.isSubmitButtonEnabled = false
        mBinding.svSearch.queryHint = "搜索行政区域关键字"
        mBinding.svSearch.findViewById<View>(androidx.appcompat.R.id.search_plate).background = null
        mBinding.svSearch.findViewById<View>(androidx.appcompat.R.id.submit_area).background = null
        mBinding.svSearch.setOnQueryTextListener(this)

        mBinding.mapView.onCreate(bundle)
        if (!this::aMap.isInitialized) {
            aMap = mBinding.mapView.map
        }
        initMapLocation()

        if (!TextUtils.isEmpty(name)) {
            mBinding.sbArea.isEnabled = false
            mBinding.sbArea.rightText = name
            searchStr = name
            getTitleBar().rightTitle = ""
            // 行政边界
            searchDistrict(searchStr!!)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mBinding.mapView.onSaveInstanceState(outState)
    }

    override fun onResume() {
        super.onResume()
        mBinding.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mBinding.mapView.onPause()
    }

    override fun onDestroy() {
        mBinding.mapView.onDestroy()
        super.onDestroy()
    }

    /**
     * 初始化地图定位
     */
    private fun initMapLocation() {
        val myLocationStyle = MyLocationStyle()
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        // locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.em_unread_count_bg));
        myLocationStyle.strokeColor(Color.BLACK)
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180))
        myLocationStyle.strokeWidth(1.0f)
        // 缩放比例
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16f))
        // 设置定位蓝点的Style
        aMap.myLocationStyle = myLocationStyle
        // 设置默认定位按钮是否显示
        aMap.uiSettings.isMyLocationButtonEnabled = true
        // 设置缩放按钮是否显示
        aMap.uiSettings.isZoomControlsEnabled = false
        // 设置比例尺控件是否显示
        aMap.uiSettings.isScaleControlsEnabled = false
        // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位
        aMap.isMyLocationEnabled = true
    }

    override fun onClick(v: View) {
        if (v.id == com.sx.pipeline.R.id.sb_area) {
            showProvincesDialog()
        } else if (v.id == com.sx.pipeline.R.id.tv_search) {
            searchDistrict(searchStr!!)
        }
    }

    override fun onQueryTextSubmit(query: String?): Boolean {
        Logs.d("onQueryTextSubmit $query")
        return false
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        searchStr = newText
        return true
    }

    /**
     * 搜索行政区
     */
    private fun searchDistrict(searchName: String, provincesName: String? = null, address: String? = null) {
        val search = DistrictSearch(this)
        val query = DistrictSearchQuery(provincesName, DistrictSearchQuery.KEYWORDS_CITY, 0)
        // 是否返回边界值
        query.isShowBoundary = true
        //不显示子区域边界
        query.isShowChild = false
        query.keywords = searchName
        search.query = query
        search.setOnDistrictSearchListener { districtResult ->
            if (districtResult?.district != null) {
                if (districtResult.aMapException.errorCode == AMapException.CODE_AMAP_SUCCESS) {
                    Logs.d("polygonDraw: " + districtResult.pageCount)
                    Logs.d("polygonDraw: " + districtResult.district.size)
                    polygonDraw(districtResult.district, address)
                }
            }
        }
        // 开始搜索
        search.searchDistrictAsyn()
    }

    private fun polygonDraw(data: List<DistrictItem>, address: String? = null) {
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<ArrayList<LatLng>?>() {
            override fun doInBackground(): ArrayList<LatLng>? {
                districtPoints.clear()
                aMap.clear()
                val points: ArrayList<LatLng> = ArrayList()
                if (data.isNotEmpty()) {
                    val boundary = data[0].districtBoundary()
                    Logs.d("polygonDraw ${boundary.size}")
                    if (boundary.isNotEmpty()) {
                        val center = data[0].center
                        var index = 0
                        var count = 0
                        for (i in boundary.indices) {
                            if (boundary[i].length >= count) {
                                count = boundary[i].length
                                index = i
                            }
                        }
                        val str = boundary[index]
                        val latLngList = str.split(";".toRegex()).toTypedArray()
                        for (element in latLngList) {
                            val latLngStr: List<String> = element.split(",")
                            if (latLngStr.size == 2) {
                                try {
                                    val lng = latLngStr[0].toDouble()
                                    val lat = latLngStr[1].toDouble()
                                    points.add(LatLng(lat, lng))
                                } catch (e: Exception) {
                                    Logs.e("onDistrictSearched: cast error")
                                }
                            }
                        }
                        //移动到marker位置
                        val mCameraUpdate: CameraUpdate = CameraUpdateFactory.newCameraPosition(
                            CameraPosition(
                                LatLng(center.latitude, center.longitude),
                                8f,
                                0f,
                                0f
                            )
                        )
                        aMap.moveCamera(mCameraUpdate)
                    } else {
                        ToastUtils.showShort("无法查询到行政边界")
                    }
                    return points
                }
                return null
            }

            override fun onSuccess(result: ArrayList<LatLng>?) {
                if (!result.isNullOrEmpty()) {
                    // 收回软件盘
                    KeyboardUtils.hideSoftInput(window)
                    // 绘制行政区
                    districtPoints = result
                    //显示行政区域范围
                    aMap.addPolyline(
                        PolylineOptions()
                            .addAll(result)
                            .width(10f)
                            .color(Color.BLUE)
                            .setDottedLine(false)
                    )
                    if (!TextUtils.isEmpty(address)) {
                        // 显示地址
                        mBinding.sbArea.rightText = "$address"
                    }
                } else {
                    // 显示地址
                    mBinding.sbArea.rightText = "无法查询到行政边界"
                }
            }

            override fun onCancel() {

            }

            override fun onFail(t: Throwable?) {

            }

        })
    }

    /**
     * 省市区选择
     */
    private fun showProvincesDialog() {
        val popup = MyCityPickerPopup(ActivityUtils.getTopActivity())
        popup.setCityPickerListener(object : MyCityPickerListener {
            override fun onCityConfirm(
                provincesVO: ProvincesVO?, cityVO: ProvincesVO?, areaVO: ProvincesVO?,
                province: String?, city: String?, area: String?, v: View?,
            ) {
                Log.d("fdsafa","省level=${provincesVO!!.name}市level=${cityVO!!.name}区level=${areaVO!!.name}")
                Log.d("fdsafa","省level=${province}市level=${city}level=${area}")
                searchStr = if (province!! == "全国") {
                    ""
                } else {
                    if (city == "全部") {
                        province
                    } else {
                        if (city == "深圳市") {
                            if (area == "南山区") {
                                districtPoints.clear()
                                aMap.clear()
                                // 显示地址
                                mBinding.sbArea.rightText = "无法查询到行政边界"
                                ToastUtils.showShort("无法查询到行政边界")
                                return
                            }
                        } else if (city == "东莞市" || city == "中山市") {
                            searchStr = city
                        } else {
                            searchStr = if (area == "全部") {
                                city
                            } else {
                                area
                            }
                        }
                        searchStr
                    }
                }

                // 省市区ID
                mViewModel.provinceIDField.set(provincesVO.id)
                mViewModel.cityIDField.set(cityVO.id)
                mViewModel.areaIDField.set(areaVO.id)
                // 省市区名称
                mViewModel.provinceNameField.set(province)
                mViewModel.cityNameField.set(city)
                mViewModel.areaNameField.set(area)
                // 详细
                mViewModel.addressDetailField.set("$province $city $area")
                // 区域名称
                mViewModel.nameField.set(searchStr)

                // 显示的地址
                val showAddress = "$province $city $area"
                // 搜索区域
                searchDistrict(searchStr!!, city, showAddress)
            }

            override fun onCityChange(province: String?, city: String?, area: String?) {

            }
        })
        XPopup.Builder(this).asCustom(popup).show()
    }
}